package com.kx.yooli.kx.wechat.service.wx;

import com.kx.yooli.kx.wechat.config.propertiesconf.CustomizedPropertyConfigurer;
import com.kx.yooli.kx.wechat.service.IServiceWechat;
import com.kx.yooli.kx.wechat.utils.wx.WeiXinUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author john_sqwen-childe.wen
 * date 2024/6/4
 * PROJECT_NAME wechat
 * description create ServiceWechatImpl by john_sqwen
 * and  value is
 */
@Service
public class ServiceWechatImpl implements IServiceWechat {
    private final Logger log = LoggerFactory.getLogger(ServiceWechatImpl.class);
    public   final String token = CustomizedPropertyConfigurer.getContextProperty("token");
    @Override
    public String processAnswer(HttpServletRequest request,HttpServletResponse response) {
        if("GET".equals(request.getMethod())){
            //token认证
            return signWechat(request);
        }else{
            return processAnswer(request,response);
        }

    }
    private String signWechat(HttpServletRequest request){
        String signature=request.getParameter("signature");
        String timestamp=request.getParameter("timestamp");
        String nonce=request.getParameter("nonce");
        String echostr=request.getParameter("echostr");
        log.info("token 验证参数:signature="+signature+" timestamp="+timestamp+" nonce="+nonce+" echostr="+echostr);
        if(null!= timestamp &&null!= nonce &&null!= echostr&&null!= signature){
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if(WeiXinUtils.checkSignature(signature, timestamp, nonce,token)){
                return echostr;
            }
        }
        return "";
    }
}
